package com.igeek.health.config;

import com.igeek.health.job.CleanImgJob;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

/**
 * @Description 定时器配置类
 * @Author chenmin
 * @Version 1.0
 * @Date 2023/2/21 15:43
 */
@ComponentScan("com.igeek.health.job")
public class QuartzConfig {

    @Autowired
    private CleanImgJob cleanImgJob;

    //JobDetail  注册一个任务，即具体要执行的业务逻辑
    @Bean
    public JobDetail jobDetail() throws Exception {
        MethodInvokingJobDetailFactoryBean jobDetail = new MethodInvokingJobDetailFactoryBean();
        //添加任务对象
        jobDetail.setTargetObject(cleanImgJob);
        //添加执行任务的方法
        jobDetail.setTargetMethod("clearImg");
        jobDetail.afterPropertiesSet();
        return jobDetail.getObject();
    }

    //CronTrigger 注册一个触发器，指定任务触发的时间
    @Bean
    public CronTrigger cronTrigger() throws Exception {
        CronTriggerFactoryBean myTrigger = new CronTriggerFactoryBean();
        //注册执行的任务
        myTrigger.setJobDetail(jobDetail());
        //任务的时间调度
        //每天凌晨两点 执行定时任务
        //myTrigger.setCronExpression("0 0 2 * * ?");
        //每隔20s 执行定时任务
        myTrigger.setCronExpression("0/20 * * * * ?");
        myTrigger.afterPropertiesSet();
        return myTrigger.getObject();
    }

    //Schedule 注册一个调度器，通过这个调度工厂调度任务
    @Bean
    public Scheduler scheduler() throws Exception {
        SchedulerFactoryBean scheduler = new SchedulerFactoryBean();
        //设置触发器
        scheduler.setTriggers(cronTrigger());
        scheduler.afterPropertiesSet();
        //启动调度器
        scheduler.start();
        return scheduler.getObject();
    }
}
